<template>
  <div class="allbk" style="padding: 10px; border-radius: 8px">
    <div v-if="!hidequery" class="w100 querybox">
      <querybox @query="query" class="h100" :queryList="queryList"></querybox>
    </div>
    <div
      :style="{ height: state.vxeHeight + 25 + 'px' }"
      :class="{ w100: true }"
      class="table_box"
    >
      <div
        :style="{ height: !hideexport || exportDataUrl ? 40 + 'px' : 0 }"
        class="w100 fsc"
      >
        <div class="crud_Box">
          <h3
            v-if="pageName != ''"
            :style="{ fontSize: store.sizeNum + 2 + 'px' }"
          >
            {{ pageName }}
            <slot name="selectName"></slot>
          </h3>
          <el-radio-group v-model="tabName" v-else @change="tabChange">
            <el-radio-button
              v-for="item in tabList"
              :label="item.name"
              :value="item.tabIndex"
              :key="item"
            />
          </el-radio-group>
          <div class="crud_desc">
            <slot name="opraCurdBtnAll" v-if="state.modify"></slot>
            <div
              v-show="!hidesetting"
              style="
                line-height: 0;
                color: rgba(64, 158, 255, 1);
                font-size: 14px;
                display: flex;
                align-items: center;
                border-radius: 0 0 8px 8px;
              "
              @click.stop="pageSet"
            >
              <!-- <svg-icon class-name="search-icon" style="fill:rgba(64, 158, 255, 1);font-size:14px;" icon-class="system"
                 /> -->
              <!-- <el-icon><Tools /></el-icon> -->
              <el-button style="margin: 0" type="primary" link>
                <el-icon><Tools /></el-icon>表格设置
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div
        class="w100 hhhhh"
        :style="{
          height:
            !hideexport || exportDataUrl
              ? state.vxeHeight - 108 + 'px'
              : state.vxeHeight + 'px',
        }"
      >
        <!-- height="auto" -->
        <vxe-table
          :row-style="rowStyle"
          class="globalFontSize"
          header-row-class-name="header"
          :loading="loading"
          height="auto"
          ref="xGrid"
          @checkbox-change="checkchange"
          :data="tabledata"
          border="inner"
          @toggle-row-expand="toggleExpandChangeEvent"
          cell-class-name="rowHeight"
        >
          <vxe-column type="checkbox" :width="50"></vxe-column>
          <vxe-column
            type="expand"
            width="80"
            :fixed="expandFixed"
            v-if="expandFixed"
          >
            <template #content="{ row, rowIndex }">
              <slot name="content" :row="row"></slot>
            </template>
          </vxe-column>
          <vxe-column type="seq" :width="55" title="序号"></vxe-column>
          <vxe-column
            v-for="(item, index) in tableheads_show"
            :field="item.field"
            :title="item.title"
            :params="{ name: item.name }"
            :width="item.width ? item.width : ''"
            :key="index"
          >
            <!-- 基础配置/出厂特性-开关量-常态逻辑 -->
            <template
              v-if="item.field == 'normalLogic' && tabName == '开关量'"
              #default="{ row }"
            >
              <span>
                {{ row["normalLogic"] == "0" ? "低电平" : "高电平" }}</span
              >
            </template>
            <!-- 基础配置/出厂特性-开关量-引用状态 -->
            <template
              v-if="item.field === 'subIndex' && tabName == '开关量'"
              #default="{ row }"
            >
              <span>
                <el-tag v-if="row['subIndex'] == '0'" type="warning"
                  >未开启</el-tag
                >
                <el-tag v-if="row['subIndex'] == '1'" type="success"
                  >已开启</el-tag
                >
              </span>
            </template>
            <!-- 历史设备/分站故障记录 -->
            <template
              v-if="item.field == 'faultType' && pageName == '分站异常记录'"
              #default="{ row }"
            >
              <span>
                {{ row["faultType"] == "0" ? "网络故障" : "分站故障" }}
              </span>
            </template>
            <!-- 历史设备/历史测点 -->
            <template
              v-if="item.field == 'sensorPlace' && pageName == '历史测点记录'"
              #default="{ row }"
            >
              <span v-for="item in state.placeList" :key="item.value">
                {{ row["sensorPlace"] == item.value ? item.label : " " }}
              </span>
            </template>
            <template
              v-if="item.field == 'operateType' && pageName == '历史测点记录'"
              #default="{ row }"
            >
              <span>
                {{
                  row["operateType"] == 1
                    ? "新增"
                    : row["operateType"] == 2
                    ? "编辑"
                    : row["operateType"] == 3
                    ? "删除"
                    : ""
                }}
              </span>
            </template>
            <!-- 历史设备/历史分站 -->
            <template
              v-if="item.field == 'ipAddress' && pageName == '历史分站'"
              #default="{ row }"
            >
              <span> {{ row["ipAddress"] + ":" }}{{ row["port"] }} </span>
            </template>
            <template
              v-if="item.field == 'replaceId' && pageName == '历史分站'"
              #default="{ row }"
            >
              <span v-for="item in state.placeList" :key="item.value">
                {{ row["replaceId"] == item.value ? item.label : " " }}
              </span>
            </template>
            <template
              v-if="item.field == 'operateType' && pageName == '历史分站'"
              #default="{ row }"
            >
              <span>
                {{
                  row["operateType"] == 1
                    ? "新增"
                    : row["operateType"] == 2
                    ? "编辑"
                    : row["operateType"] == 3
                    ? "删除"
                    : ""
                }}
              </span>
            </template>
            <!-- 历史设备/测点故障记录 -->
            <template
              v-if="item.field == 'faultType' && pageName == '测点异常记录'"
              #default="{ row }"
            >
              <span> {{  row["faultType"]=='0'?'报警':row["faultType"]=='1'?'故障':row["faultType"]=='2'?'断电':'' }} </span>
            </template>
                    <!-- 历史设备/电源故障记录 -->
                    <template
              v-if="item.field == 'faultType' && pageName == '电源异常记录'"
              #default="{ row }"
            >
              <span> {{  row["faultType"]=='0'?'主电欠压':row["faultType"]=='1'?'备电欠压':'' }} </span>
            </template>
            <!-- <template v-if="item.field === 'imagePath'" #default="{ row }">
              <img :src="row.imagePath" style="width: 80px;height: 40px;" alt="">
            </template>
            <template v-if="item.field === 'substationNumber'" #default="{ row }">
              <span>
                {{ row.substationNumber }}
              </span>
            </template> -->
          </vxe-column>
          <vxe-column
            title="操作"
            v-if="state.modify && isShowCaozuo"
            width="150"
          >
            <template #default="{ row }">
              <slot name="opraCurdBtn" :row="row"></slot>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <div
      v-if="!hidepage"
      class="w100 pagevxe"
      style="position: relative; height: 35px"
    >
      <el-pagination
        class="pages globalFontSize"
        v-model:current-page="pageconfig.currentPage"
        v-model:page-size="pageconfig.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageconfig.total"
        @size-change="pagechange"
        @current-change="pagechange"
        style="
          position: absolute;
          bottom: 16px;
          right: 16px;
          background-color: rgba(255, 255, 255, 0.8);
        "
      />
      <!-- <vxe-pager @page-change="pagechange" background align="right" style="position: absolute;bottom:6px;right:16px;background-color: rgba(255, 255, 255, .8);"
        :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
        v-model:current-page="pageconfig.currentPage" v-model:page-size="pageconfig.pageSize" :total="pageconfig.total">
      </vxe-pager> -->
    </div>

    <!--表格设置-->
    <teleport to="body">
      <vxe-modal
        @close="saveSet"
        esc-closable
        destroy-on-close
        :lock-view="false"
        :width="700"
        :height="500"
        v-model="state.open_pageSet"
        resize
        :mask="true"
      >
        <template #title>
          <div class="w100 h100 fsc" style="height: 22px">表格设置</div>
        </template>
        <template #default>
          <div class="w100 h100 biaogeshezhi" style="padding: 12px">
            <!-- <div class="w100 fcc" style="height: 40px">
              <el-switch
                  v-model="state.moshi"
                  size="large"
                  active-text="实时数据自动刷新"
                  inactive-text="实时数据手动刷新"
                  @change="moshichange"
              />
            </div> -->
            <div class="w100" style="height: calc(100% - 40px)">
              <vxe-table
                height="auto"
                :data="tableheads"
                :row-style="rowStyle"
                border="inner"
              >
                <vxe-column title="列名" field="title"></vxe-column>
                <vxe-column title="是否显示" field="show">
                  <template #default="{ row }">
                    <vxe-switch
                      v-model="row.show"
                      :close-value="0"
                      :open-value="1"
                      open-label="是"
                      close-label="否"
                    >
                    </vxe-switch>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </div>
        </template>
      </vxe-modal>
    </teleport>
  </div>
</template>
<script>
import querybox from "./querybox";
import Sortable from "sortablejs";
import {
  computed,
  nextTick,
  onActivated,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  inject,
} from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "@/utils/request";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import usePagesStore from "@/store/modules/pages";
import { getToken } from "@/utils/auth";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
import dayjs from "dayjs";
export default {
  name: "vxeTB",
  components: {
    querybox,
  },
  props: {
    pageName: {
      default: () => "",
      type: String,
    },
    tabName: {
      default: () => "",
      type: String,
    },

    delBtnMul: {
      default: () => false,
      type: Boolean,
    },
    showradio: {
      default: () => false,
      type: Boolean,
    },
    loading: {
      default: () => false,
      type: Boolean,
    },
    showcheck: {
      default: () => false,
      type: Boolean,
    },
    tabledata: {
      default: () => [],
      require: true,
    },
    tableheads: {
      default: () => [],
      require: true,
    },
    queryList: {
      default: () => [],
    },
    tabList: {
      default: () => [],
    },
    pageconfig: {
      default: () => {
        return {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        };
      },
      require: true,
    },
    hidequery: {
      default: () => false,
      type: Boolean,
    },
    // 展开
    expandFixed: {
      default: () => false,
      type: Boolean,
    },
    hidepage: {
      default: () => false,
      type: Boolean,
    },
    showduoyulan: {
      default: () => false,
      type: Boolean,
    },
    exportUrl: {
      default: () => "",
    },
    exportDataUrl: {
      default: () => "",
    },
    importUrl: {
      default: () => "",
    },
    dataUrl: {
      default: () => "",
    },
    getUrl: {
      default: () => "",
    },
    echartsUrl: {
      default: () => "",
    },
    setTopUrl: {
      default: () => "",
    },
    unsetTopUrl: {
      default: () => "",
    },
    hideexport: {
      default: () => false,
      type: Boolean,
    },
    chakanxiangqing: {
      default: () => false,
      type: Boolean,
    },
    leftTableShow: {
      default: () => false,
      type: Boolean,
    },
    hidesetting: {
      default: () => false,
      type: Boolean,
    },
    isShowCaozuo: {
      default: () => false,
      type: Boolean,
    },
  },
  setup(props, { emit }) {
    const base_url = import.meta.env.VITE_APP_BASE_API;
    const store = usePagesStore();
    let baseurl = import.meta.env.VITE_APP_BASE_API;
    const router = useRouter();
    const storageSetting2 = JSON.parse(localStorage.getItem("layout-set"));
    let xGrid = ref(null);
    let state = reactive({
      modify: userStore.modify,
      vxeHeight: 500,
      open_pageSet: false,
      open_daoru: false,
      open_chakanxiangqing: false,
      chakanxiangqingList: {},
      moshi: false,
      personPhotoInfo: "",
      records: [],
      placeList: [], //安装地点
    });
    // 数组去重
    function unique(arr, key) {
      const res = new Map();
      return arr.filter((a) => !res.has(a[key]) && res.set(a[key], 1));
    }
    let tableheads_show = computed(() => {
      return unique(
        props.tableheads.filter((i) => i.show === 1),
        "field"
      );
    });
    let tabName = computed(() => {
      return props.tabName;
    });
    /**
     * 刷新开关
     * @param {} e
     */
    function moshichange(e) {
      localStorage.setItem("moshi", e);
    }
    // 查询数据
    function query() {
      emit("query");
    }
    // 改变分页
    function pagechange() {
      console.log(props.pageconfig);

      emit("pagechange", props.pageconfig);
    }
    /**
     * 列表操作中增删改查按钮
     */
    function btnClick(type, row) {
      emit(type, row);
    }

    function tabChange(val) {
      emit("tabChange", val);
    }
    function yinyong(row) {
      emit("yinyong", row);
    }

    function checkchange(e) {
      state.records = e.records;
      store.records = e.records;
    }
    const toggleExpandChangeEvent = ({ expanded }) => {
      console.log("行展开事件" + expanded);
    };
    /**
     * 列表设置
     * @param {*} fullColumn
     */
    function setHeaders(fullColumn) {
      let newfullColumn = fullColumn.filter((item) => {
        return item.params !== undefined;
      });
      axios
        .post(
          "/vxeheaders/setHeaders",
          props.tableheads
          // newfullColumn.map((item, index) => {
          //   return {
          //     name: item.params.name,
          //     width: String(item.width),
          //     type: item.type,
          //     field: item.field,
          //     title: item.title,
          //     sort: (index),
          //     show: "1",
          //   }
          // })
        )
        .then(() => {
          ElMessage.success("设置成功");
        });
    }

    function resizeChange(e) {
      const { fullColumn } = e.$table.getTableColumn();
      fullColumn[e.columnIndex].width = fullColumn[e.columnIndex].renderWidth;
      setHeaders(fullColumn);
    }

    function pageSet() {
      state.open_pageSet = true;
    }

    function saveSet() {
      const { fullColumn } = xGrid.value.getTableColumn();
      setHeaders(fullColumn);
    }

    function setVxeHeight() {
      let allbk = document.getElementsByClassName("allbk")[0];
      let querycss = document.getElementsByClassName("querycss")[0];
      if (querycss) {
        state.vxeHeight =
          allbk.getBoundingClientRect().height -
          querycss.getBoundingClientRect().height -
          85;
      } else {
        state.vxeHeight = allbk.getBoundingClientRect().height - 85;
      }
    }

    function columnDrop2(dom) {
      Sortable.create(
        dom.$el.querySelector(
          ".body--wrapper>.vxe-table--header .vxe-header--row"
        ),
        {
          handle: ".vxe-header--column:not(.col--fixed)",
          onEnd: (sortableEvent) => {
            const targetThElem = sortableEvent.item;
            const newIndex = sortableEvent.newIndex;
            const oldIndex = sortableEvent.oldIndex;
            const { fullColumn, tableColumn } = dom.getTableColumn();
            const wrapperElem = targetThElem.parentNode;
            const newColumn = fullColumn[newIndex];
            if (newColumn.fixed) {
              // 错误的移动
              const oldTrElement = wrapperElem.children[oldIndex];
              if (newIndex > oldIndex) {
                wrapperElem.insertBefore(targetThElem, oldTrElement);
              } else {
                wrapperElem.insertBefore(oldTrElement, targetThElem);
              }
              ElMessage.error("不能拖动固定列");
            }
            // 转换真实索引
            const oldColumnIndex = dom.getColumnIndex(tableColumn[oldIndex]);
            const newColumnIndex = dom.getColumnIndex(tableColumn[newIndex]);
            // 移动到目标列
            const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
            fullColumn.splice(newColumnIndex, 0, currRow);
            dom.loadColumn(fullColumn);
            setHeaders(fullColumn);
          },
        }
      );
    }

    // 是否添加排序
    const addsort = (obj) => {
      let bl = false;
      if (obj.field == "primaryIndexId") {
        bl = true;
        // console.log(obj.name,bl);
      } else if (obj.field == "refStatus") {
        bl = true;
      } else if (obj.field == "normalLogicName") {
        bl = true;
      } else {
        bl = false;
      }
      return bl;
    };
    function rowStyle({ row, rowIndex }) {
      if (rowIndex % 2 !== 0) {
        return { "background-color": "#f0f3f9" };
      } else {
        return { "background-color": "" };
      }
    }
    function getSelectList() {
      let arr = [];
      axios.post("/gas/place/list", {}).then((res) => {
        arr = res.rows?.map((item) => {
          return { value: item.id + "", label: item.address };
        });
        state.placeList = arr;
        // state.options.queryList.querys[2].options = arr;
      });
    }
    onMounted(() => {
      setVxeHeight();
      window.onresize = () => {
        setVxeHeight();
      };
      getSelectList();
      // columnDrop2(xGrid.value)
    });
    return {
      rowStyle,
      moshichange,
      unique,
      base_url,
      saveSet,
      tableheads_show,
      tabName,
      pageSet,
      state,
      emit,
      router,
      // resizeChange,
      xGrid,
      pagechange,
      query,
      store,
      getToken,
      baseurl,
      checkchange,
      btnClick,
      tabChange,
      toggleExpandChangeEvent,
      yinyong,
      addsort,
      storageSetting2,
    };
  },
};
</script>
<style lang="scss">
.querybox {
  margin: 0 0 10px 0;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 8px;
  box-shadow: -6px 2px 6px rgba(0, 0, 0, 0.02);
}

.table_box {
  background-color: rgba(255, 255, 255, 1);
  // border-radius: 8px;
  border-radius: 8px 8px 0 0;
  padding: 10px;
  box-shadow: -6px 2px 6px rgba(0, 0, 0, 0.02);
}

.pagevxe {
  background-color: rgba(255, 255, 255, 1);
  box-shadow: -6px 2px 6px rgba(0, 0, 0, 0.02);
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.crud_Box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 12px 0;
  h3 {
    font-size: 16px;
    font-weight: 700;
  }

  .crud_desc {
    .btn {
      margin: 0 10px;
    }
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}

.chakanxiangqing {
  .box {
    display: flex;
    flex-wrap: wrap;
    border: 1px solid #e7e7e7;
    padding: 10px;

    .boxList {
      padding: 4px 0;
      width: 50%;
      border-bottom: 1px solid #e7e7e7;

      span {
        &:nth-child(1) {
          font-size: 14px;
          font-weight: bold;
        }
      }
    }
  }
}

.el-steps--horizontal {
  display: contents;
}

.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss">
// @import "@/assets/styles/page-edit.scss";
// .vxe-table--render-default .vxe-body--row.row--stripe {
//   background-color: #{$stripe-bg}; /* 修改为你想要的背景色 */
// }
.globalFontSize {
  font-size: 14px !important;
}
.biaogeshezhi {
  .vxe-table--body-wrapper.body--wrapper {
    box-shadow: 0px -10px 10px #ccc inset;
  }
}

.boxddd {
  margin-left: -10px;
  // border-bottom: 1px solid #E7E7E7;
  padding: 1px 0 1px 10px;
  width: 140%;
  text-align: left;
}

.leftpart {
  margin-left: 12%;
  width: 350px;
  overflow: scroll;
}

.rightpart {
  flex: 1;
  width: calc(100% - 125px);
}

.allbk {
  // background: white;
  position: relative;
  box-shadow: 0px 2px 16px rgba(0, 0, 0, 0.02);
}

.height100p {
  height: calc(100% - 5px) !important;
}

.height100p-100 {
  height: calc(100% - 100px);
}

.height100p-50 {
  height: calc(100% - 50px);
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.vmodel_mulu {
  position: absolute;
  top: 100px;
  left: 300px;
  width: 500px;
  height: 500px;
  background: #cccccc;
  border: 1px solid #1d376b;
}
</style>